package cn.fl.ref.fncprjprdpaysch.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.ref.fncprjprdpaysch.service.IFncPrjPrdPaySchDService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapOverdueInfoQueryCondition;
import cn.fl.capital.vo.CapOverdueInfoVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjPrdPaySchDConstant;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.constant.PrjQuatPrpsFeeConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.ref.fncprjprdpaysch.service.IFncPrjPrdPaySchMService;
import cn.fl.ref.fncprjprdpaysch.vo.FncPrjPrdPaySchDVO;
import cn.fl.ref.fncprjprdpaysch.vo.FncPrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import fl.ref.fncprjprdpaysch.condition.FncPrjPrdPaySchMQueryCondition;
import fl.ref.fncprjprdpaysch.service.IFncPrjPrdPaySchMApiService;

/**
 * @Description: 项目产品支付表主信息表 控制层
 */
@Controller
@RequestMapping("/ref/fncprjprdpaysch/fncPrjPrdPaySchM")
public class FncPrjPrdPaySchMController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(FncPrjPrdPaySchMController.class);
   
    /**
     * PrjPrdPaySchM 服务层BEAN
     */
    @Autowired
    private IFncPrjPrdPaySchMService fncPrjPrdPaySchMService;
    @Autowired
	private IFncPrjPrdPaySchMApiService fncPrjPrdPaySchMApiService;
    @Autowired
	private IFncPrjPrdPaySchDService fncPrjPrdPaySchDService;

    /**
     * 项目基础服务
     */
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    /**
     * 客户
     */
    @Autowired
    private ICstBscInfoService cstBscInfoService;
    /**
     * 到支付表管理列表页面
     */
    @RequestMapping(value = "/toPrjPrdPaySchMMgrPage.do", method = {RequestMethod.GET})
    public ModelAndView toPrjPrdPaySchMMgrPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载PrjPrdPaySchM列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("rfbuss/fncprjprdpaysch/prjPrdPaySchMMgrPage");
        //项目类型
        List<KeyValueVO> projectTypeList = this.prjBscInfoService.getProjectTypeList();
        //业务类型
        List<KeyValueVO> bizTypeList = this.prjBscInfoService.getBizTypeList();
        // 事业部
        List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
        //业务类型
        List<KeyValueVO> prdStsCdList = this.prjBscInfoService.getPrdStsCdList();
        view.addObject("orgListList", orgList);
        view.addObject("projectTypeList", projectTypeList);
        view.addObject("bizTypeList", bizTypeList);
        view.addObject("prdStsCdList", prdStsCdList);
        view.addObject("currentBuOrgCd", CurrentThreadContext.getCurrentBuOrgCd());
        return view;
    }

    /**
     * 支付表管理
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getPrjPrdPaySchMList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getPrjPrdPaySchMList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String prjNm = request.getParameter("prjNm");//项目名称
        String splNm = request.getParameter("splNm");//供应商名称
        String prjTypCd = request.getParameter("prjTypCd");//项目类型
        String buOrgCd = request.getParameter("buOrgCd");//事业部
        String bizTypCd = request.getParameter("bizTypCd");//业务模式
        String lsDt = request.getParameter("lsDt");//起租日期
        String cstNm = request.getParameter("cstNm");//客户名称
        String lsCntNo = request.getParameter("lsCntNo");//合同编号
        String timeType = request.getParameter("timeType");//时间类型
        String strDate = request.getParameter("strDate");//开始时间
        String endDate = request.getParameter("endDate");//结束时间
        String prdStsCd = request.getParameter("prdStsCd");//支付表状态
        String paySchNo = request.getParameter("paySchNo");//支付表号
        String isDel = request.getParameter("isDel");
        String transFlg = request.getParameter("transFlg");
        String bizFlag = request.getParameter("bizFlag");

        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        FncPrjPrdPaySchMQueryCondition qc = new FncPrjPrdPaySchMQueryCondition();
        if (StringUtils.isNotBlank(prdStsCd)) {
            qc.setPrdStsCd(prdStsCd);
        }
        if (StringUtils.isNotBlank(isDel)) {
            qc.setIsDel(Integer.valueOf(isDel));
        }
        if (StringUtils.isNotBlank(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        if (StringUtils.isNotBlank(strDate)) {
            qc.setStrDt(DateUtils.formatStringToDate(strDate, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(timeType)) {
            if (timeType.equals(PrjPrdPaySchDConstant.CODE_TIME_TYPE_STL)) {
                qc.setStlDt(qc.getStrDt() == null ? null : qc.getStrDt());
            }
            if (timeType.equals(PrjPrdPaySchDConstant.CODE_TIME_TYPE_BACK)) {
                qc.setBackDt(qc.getStrDt() == null ? null : qc.getStrDt());
            }
            if (timeType.equals(PrjPrdPaySchDConstant.CODE_TIME_TYPE_FORM)) {
                qc.setFormDt(qc.getStrDt() == null ? null : qc.getStrDt());
            }
        }
        if (StringUtils.isNotBlank(endDate)) {
            qc.setEndDt(DateUtils.formatStringToDate(endDate, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotBlank(lsCntNo)) {
            qc.setLsCntNo(lsCntNo);
        }
        if (StringUtils.isNotEmpty(prjNm)) {
            qc.setPrjNm(prjNm);
        }
        if (StringUtils.isNotEmpty(splNm)) {
            qc.setSplNm(splNm);
        }
        if (StringUtils.isNotEmpty(prjTypCd)) {
            qc.setPrjTypCd(prjTypCd);
        }
        if (StringUtils.isNotEmpty(buOrgCd)) {
            qc.setBuOrgCd(buOrgCd);
        }
        if (StringUtils.isNotEmpty(bizTypCd)) {
            qc.setBizTypCd(bizTypCd);
        }
        if (StringUtils.isNotEmpty(transFlg)) {
            qc.setTransFlg(Long.valueOf(transFlg));
        }
        if (StringUtils.isNotEmpty(lsDt)) {
            qc.setLsDt(DateUtils.formatStringToDate(lsDt, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(bizFlag)) {
            qc.setBizFlag(bizFlag);
        }
        String prjId=request.getParameter("prjId");
        if (StringUtils.isNotBlank(prjId)) {
			qc.setPrjId(Long.valueOf(prjId));
		}
        qc.setUsrId(CurrentThreadContext.getCurrentUserId());
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        page.setCondition(qc);
        BaseLogUtils.info(logger, "initPrjPrdPaySchMList", "初始化PrjPrdPaySchM列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = null;
        if (StringUtils.isNotBlank(isDel) && isDel.equals(BaseConstant.IS_YESNO_YES)) {
            BaseLogUtils.info(logger, "getPrjPrdPaySchMList", "AAAA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
            
            pager = this.fncPrjPrdPaySchMService.selectFncPrjPrdPaySchMMgrListPage(page);
        } else {
            BaseLogUtils.info(logger, "getPrjPrdPaySchMList", "BBBB:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
            pager = this.fncPrjPrdPaySchMService.selectFncPrjPrdPaySchMMgrListPage(page);
        }
        List<FncPrjPrdPaySchMVO> list = (List<FncPrjPrdPaySchMVO>) pager.getResultList();
        BaseLogUtils.info(logger, "getPrjPrdPaySchMList", "支付表管理list:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
        ListPageVO<FncPrjPrdPaySchMVO> listPage = new ListPageVO<FncPrjPrdPaySchMVO>(list, pager.getTotalCount());
        return listPage;
    }
    /**
     * 到详细页面
     */
    @RequestMapping(value = "/toPrjPrdPaySchMDetailPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toPrjPrdPaySchMDetailPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toPrjPrdPaySchMDetailPage", "加载toPrjPrdPaySchMDetailPage Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("rfbuss/fncprjprdpaysch/prjPrdPaySchMDetailPage");
        String id = request.getParameter("id");
        FncPrjPrdPaySchMVO vo = null;
        CapOverdueInfoVO cap = null;
        double totalPardUpAmt = 0d;
        double totalRntAmt = 0d;
        List<FncPrjPrdPaySchDVO> payList = new ArrayList<FncPrjPrdPaySchDVO>();
        ListPageVO<FncPrjPrdPaySchDVO> listPage = null;
        if (StringUtils.isNotBlank(id)) {
            vo = this.fncPrjPrdPaySchMService.selectPrjPrdPaySchMAndDetailById(Long.valueOf(id));

//            Long sid = null;
//            PrjPrdPaySchTMQC qc = new PrjPrdPaySchTMQC();
//            qc.setPrjId(vo.getPrjId());
//            List<PrjPrdPaySchTMVO> prjPrdPaySchTMVOs = this.fncPrjPrdPaySchTMService.searchList(qc);
//            if (CollectionUtils.isNotEmpty(prjPrdPaySchTMVOs)) {
//                sid = prjPrdPaySchTMVOs.get(0).getId();
//                mav.addObject("isClx", 1);
//            }
            Long cumtomerPayId = null;
            FncPrjPrdPaySchMQueryCondition qc1 = new FncPrjPrdPaySchMQueryCondition();
            qc1.setPrjId(vo.getPrjId());
            qc1.setIsSqBiz(BaseConstant.IS_YESNO_NO);
            List<FncPrjPrdPaySchMVO> cumtomerPayList = this.fncPrjPrdPaySchMService.searchList(qc1);
            if (CollectionUtils.isNotEmpty(cumtomerPayList)) {
                cumtomerPayId = cumtomerPayList.get(0).getId();
                mav.addObject("isCumtomerPay", 1);
            }
            mav.addObject("cumtomerPayId", cumtomerPayId);
           // mav.addObject("sid", sid);

            CapOverdueInfoQueryCondition capQc = new CapOverdueInfoQueryCondition();
            capQc.setIsDel(BaseConstant.IS_YESNO_NO);
            capQc.setPaySchId(Long.valueOf(id));
            capQc.setOverdueStatusCd(BaseConstant.IS_YESNO_NO + "");
            capQc.setCreateDate(new Date());
            List<CapOverdueInfoVO> capList = null;
            if (CollectionUtils.isNotEmpty(vo.getPrjPrdPaySchDList())) {
                List<FncPrjPrdPaySchDVO> list = vo.getPrjPrdPaySchDList();
                List<FncPrjPrdPaySchDVO> totalList = new ArrayList<FncPrjPrdPaySchDVO>();
                for (FncPrjPrdPaySchDVO detail : vo.getFeeDetailList()) {
                    if (detail.getCntWayCd().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CNT_WAY_DOWNPAY)) {
                        totalList.add(detail);
                    }
                    if (null != detail.getFeeTypCd() && (detail.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.CODE_FEE_WAY_TYPE_RICK_DEP) || detail.getFeeTypCd().equals(PrjQuatPrpsFeeConstant.FEE_TYP_CD_104))) {
                        totalList.add(detail);
                    }
                }
                totalList.addAll(list);
                for (FncPrjPrdPaySchDVO prjPrdPaySchDVO : totalList) {
                   
                    if (prjPrdPaySchDVO.getPayPd() == PrjQuatPrpsConstant.CODE_PRJ_PRD_FEE_PD.intValue() || prjPrdPaySchDVO.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_RNT_PRICE)) {
                        payList.add(prjPrdPaySchDVO);
                        //计算合计信息
                        double paidUpAmt = DecimalUtils.convertFenToYuan(prjPrdPaySchDVO.getPaidUpAmt());
                        totalPardUpAmt = DecimalUtils.add(totalPardUpAmt, paidUpAmt == 0d ? 0 : paidUpAmt);

                        totalRntAmt = DecimalUtils.add(totalRntAmt, prjPrdPaySchDVO.getFeeAmt()==null?0:prjPrdPaySchDVO.getFeeAmt());
                    }
                }
                
            }

            listPage = new ListPageVO<FncPrjPrdPaySchDVO>(payList, payList.size());
            if (CollectionUtils.isNotEmpty(capList)) {
                capList.get(0);
            }
        }
        mav.addObject("listPage", JSON.toJSONString(listPage));
        mav.addObject("cap", cap);
        mav.addObject("totalPardUpAmt", totalPardUpAmt);
        mav.addObject("totalRntAmt", totalRntAmt);
        mav.addObject("id", id);
        return mav;
    }
	/**
	 * 同步
	 */
	@RequestMapping(value = "/saveSynPay.do")
	@ResponseBody
	public Object saveSynPay(HttpServletRequest request){
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		String payCode = request.getParameter("payCode");
		try {
			fncPrjPrdPaySchMApiService.saveSynPay(payCode);	
				BaseLogUtils.info(logger, "saveSynPay", "操作数据. DATA:" + JSONObject.toJSONString(payCode), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			ex.printStackTrace();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "saveSynPay", "操作数据失败.DATA:" + JSONObject.toJSONString(payCode) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

    /**
     * 到线下赎回支付表导入页面
     */
    @RequestMapping(value = "/toPrjPrdPaySchImportPage.do")
    public Object toPrjPrdPaySchImportPage(){
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toPrjPrdPaySchImportPage", "加载线下赎回支付表导入页面：" + CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("rfbuss/fncprjprdpaysch/prjPrdPaySchImport");
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toPrjPrdPaySchImportPage", "加载线下赎回支付表导入页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 上传excel并解析
     * @param upfile
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/importExcel.do",method = { RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object importExcel(@RequestParam(value = "upfile") MultipartFile upfile) throws IOException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "导入成功");
        if (null == upfile) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("模板文件为空,请选择文件");
            BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
            return result;
        }
        String fileName = upfile.getOriginalFilename();
        String[] names = fileName.split("\\.");
        if (!names[names.length - 1].toLowerCase().equals("xls") && !names[names.length - 1].toLowerCase().equals("xlsx")) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请下载模板后，按照模板格式上传");
            BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_ENABLE_FAIL, CurrentThreadContext.getCurrentUserName());
            return result;
        }
        InputStream fis = upfile.getInputStream();
        result = this.parseExcel(fis, result);
        if (BaseConstant.IS_YESNO_NO == result.getSuccess()) {
            return result;
        }
        List<PrjPrdPaySchMVO> prjPrdPaySchMList = (List<PrjPrdPaySchMVO>) result.getData();
        try {
            BaseLogUtils.info(logger, "importExcel", "操作数据. DATA:" + JSONObject.toJSONString(prjPrdPaySchMList), CurrentThreadContext.getCurrentUserName());
            fncPrjPrdPaySchDService.calculateRentForWs(prjPrdPaySchMList);
        }catch (Exception ex) {
            ex.printStackTrace();
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.error(logger, "importExcel", "操作数据失败.DATA:" + JSONObject.toJSONString(prjPrdPaySchMList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        ListPageVO<PrjPrdPaySchMVO> listPage = new ListPageVO<>(prjPrdPaySchMList, prjPrdPaySchMList.size());
        result.setData(listPage);
        return result;
    }

    /**
     * 解析读取excel里的内容
     * @param fis
     * @param result
     * @return
     */
    public DataResultVO parseExcel(InputStream fis,DataResultVO result) {
        List<PrjPrdPaySchMVO> prjPrdPaySchMList = new ArrayList<>();
        PrjPrdPaySchMVO prjPrdPaySchMVO;
        try {
            HSSFWorkbook book = new HSSFWorkbook(fis);
            HSSFSheet sheet = book.getSheetAt(0);
            int firstRow = sheet.getFirstRowNum();
            int lastRow = sheet.getLastRowNum();
            BaseLogUtils.info(logger, "parseExcel", "firstRow:"+firstRow+",lastRow:"+lastRow, CurrentThreadContext.getCurrentUserName());
            if (0 == lastRow) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("模版不能为空，请重新上传！");
                BaseLogUtils.info(logger, "parseExcel", "模版不能为空，请重新上传！", CurrentThreadContext.getCurrentUserName());
                return result;
            }
            if (lastRow > 20) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("系统最多允许一次上传20条数据，请重新上传！");
                BaseLogUtils.info(logger, "parseExcel", "系统最多允许一次上传20条数据，请重新上传！", CurrentThreadContext.getCurrentUserName());
                return result;
            }
            for (int i = 1; i <= lastRow; i++) {
                prjPrdPaySchMVO = new PrjPrdPaySchMVO();
                HSSFCell paySchNoCell = sheet.getRow(i).getCell(0);
                HSSFCell insCodeCell = sheet.getRow(i).getCell(1);
                BaseLogUtils.info(logger, "parseExcel", "paySchNoCell:"+paySchNoCell+",insCodeCell:"+insCodeCell, CurrentThreadContext.getCurrentUserName());

                if (null == paySchNoCell || null == insCodeCell) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("数据不完整，请重新上传！");
                    BaseLogUtils.info(logger, "parseExcel", "数据不完整，请重新上传！", CurrentThreadContext.getCurrentUserName());
                    return result;
                }else {
                    prjPrdPaySchMVO.setPaySchNo(paySchNoCell.getStringCellValue());
                    prjPrdPaySchMVO.setInsCode(insCodeCell.getStringCellValue());
                    prjPrdPaySchMList.add(prjPrdPaySchMVO);
                }
            }
        } catch (IOException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "parseExcel", "错误[Exception] -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
            e.getStackTrace();
        }
        result.setData(prjPrdPaySchMList);
        return result;
    }
}

